package com.cx.dubbo.interceptor;

import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cx.dubbo.utils.LogInfoUtil;
import com.cx.dubbo.utils.PropertiesUtil;

public class LoginInterceptor implements HandlerInterceptor{
	
	
	/**
	 * 该方法将在整个请求结束之后
	 * */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception arg3)
			throws Exception {
		//request.get
		
	}

	/**
	 * 当前请求进行处理之后
	 * */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 该方法将在请求处理之前进行调用
	 * */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {

		//调度接口日志
		String url = request.getServletPath();
		Enumeration<String> en =  request.getParameterNames();
		String param = "";
		while (en.hasMoreElements()) {
            String key = en.nextElement();
            param += key + ":" + request.getParameter(key)+",";
        }
		LogInfoUtil.info(this.getClass(), "function:"+url, param);
		
		//本地Session认证
		System.out.println("-----------------------");
		
		System.out.println(PropertiesUtil.getConfig().getString("LOGIN_FLAG"));
		
		System.out.println("Session_id-->>"+request.getSession().getId());
		
		System.out.println(request.getSession().getAttribute(PropertiesUtil.getConfig().getString("LOGIN_FLAG")));
		
		System.out.println(request.getSession().getId());
		
		if (request.getSession().getAttribute(PropertiesUtil.getConfig().getString("LOGIN_FLAG")) != null) {
			return true;
		}
		
		//认证不通过
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append("{\"code\":\"-1\",\"msg\":\"请求错误，请退出重新进入\"}");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (out != null) {
				out.close();
			}
		}
		return false;
	}
	
	
}
